package com.itfreer.data.check.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.itfreer.data.check.ICheck;
import com.itfreer.data.check.entity.CheckConfigEntity;
import com.itfreer.data.check.entity.CheckHistoryEntity;
import com.itfreer.data.check.entity.CheckInfo;

/**
 * 检查服务类 核心算法，基于ICheck接品进行数据检查
 * 
 * @author cai
 *
 */
@Component("baseCheckServiceImp")
public class BaseCheckServiceImp implements CheckService, ApplicationContextAware {

	protected static ApplicationContext applicationContext;

	@Autowired
	protected CheckConfigService checkConfigService;

	@Autowired
	protected CheckHistoryService checkHistoryService;

	@Override
	public List<CheckHistoryEntity> check(Object entity, CheckInfo info) {

		// 1.查询配置表
		Map<String, Object> whereMap = new HashMap<String, Object>();
		whereMap.put("name:=", info.getName());
		Map<String, Integer> orderMap = new HashMap<String, Integer>();
		orderMap.put("order", 0);
		List<CheckConfigEntity> checkConfigList = checkConfigService.getEntitys(null, whereMap, orderMap, 1000, 1);
		
		// 定义检查结果对象
		Boolean checkFlag = false;
		List<CheckHistoryEntity> checkHistoryList = new ArrayList<CheckHistoryEntity>();
		// 保存或更新前历史记录对象
		CheckHistoryEntity beforeHistory = new CheckHistoryEntity();
		// 保存或更新后历史记录对象
		CheckHistoryEntity afterHistory = new CheckHistoryEntity();
		// 说明已经进行过检查
		if (null != checkConfigList && checkConfigList.size() > 0) {
			for (CheckConfigEntity checkConfig : checkConfigList) {
				// 获取配置中节点
				String configTacheid = checkConfig.getTacheid();
				// 如果当前是当前节点下的检查事项，执行属性检查
				if (configTacheid.equals(info.getTacheid())) {
					// 获取spring中注册的bean名称
					String beanname = checkConfig.getBeanname();
					// 获取执行脚本
					String paras = checkConfig.getParas();
					// 获取实现类
					ICheck check = null;
					try {
						check = (ICheck)applicationContext.getBean(beanname);
					} catch (Exception e) {
						// TODO: handle exception
						throw new RuntimeException("没有获取到检查逻辑，无法进行检查!");
					}
					// 运行检查
					checkFlag = check.runCheck(entity, paras);
					// 组装检查记录
					beforeHistory = AssembleCheckHistory(checkConfig, info, "已检查", checkFlag);
				} else {
					beforeHistory = AssembleCheckHistory(checkConfig, info, "未检查", false);
				}

				// 保存或更新检查记录
				afterHistory = SaveOrUpdateCheckHistory(beforeHistory);
				// 把记录放入到返回结果中
				checkHistoryList.add(afterHistory);
			}
		}
		return checkHistoryList;
	}

	@Override
	public void setApplicationContext(ApplicationContext appContext) throws BeansException {
		// TODO Auto-generated method stub
		applicationContext = appContext;
	}

	/**
	 * 组装历史记录
	 * 
	 * @param checkConfig
	 *            配置数据
	 * @param dataid
	 *            数据实体主键id
	 * @param checkFlag
	 *            检查是否通过
	 * @return
	 */
	public CheckHistoryEntity AssembleCheckHistory(CheckConfigEntity checkConfig, CheckInfo info,
			String state, Boolean checkFlag) {

		CheckHistoryEntity checkHistory = new CheckHistoryEntity();
		// id值
		checkHistory.setId(java.util.UUID.randomUUID().toString().replace("-", ""));
		// 数据ID
		checkHistory.setDataid(info.getDataid().toString());
		// 环节名称
		checkHistory.setTachename(checkConfig.getTachename());
		// 检查事项名称
		checkHistory.setMatter(checkConfig.getMatter());
		// 排序号
		checkHistory.setOrder(checkConfig.getOrder());
		// 检查类型（自定义字典项）
		checkHistory.setType(checkConfig.getType());
		//检查类型名称
		checkHistory.setTypeName(checkConfig.getTypeName());
		// 检查状态（自定义字典项）
		checkHistory.setState(state);
		// 检查人姓名 
		checkHistory.setUsername(info.getUserName());
		// 检查时间
		checkHistory.setChecktime(new Date());
		// result
		if (checkFlag) {// 检查通过
			checkHistory.setResult(checkConfig.getPassresult());
			checkHistory.setConclusion("通过");
		} else if (!checkFlag && "已检查".equals(state)) {// 已检查、未通过
			checkHistory.setResult(checkConfig.getUnpassresult());
			checkHistory.setConclusion("未通过");
		} else {
			checkHistory.setResult("");
			checkHistory.setConclusion("未检查");// 未检查
		}
		// 备注说明 remarks;
		return checkHistory;
	}

	/**
	 * 更新或保存历史记录
	 * 
	 * @param checkHistory
	 * @return
	 */
	public CheckHistoryEntity SaveOrUpdateCheckHistory(CheckHistoryEntity checkHistory) {

		if (checkHistory == null) {
			return null;
		}
		CheckHistoryEntity returnCheckHistoryEntity = new CheckHistoryEntity();
		String dataid = checkHistory.getDataid();
		// 1.根据数据实体id和具体检查事项名称，查询历史记录表
		Map<String, Object> whereMap = new HashMap<String, Object>();
		whereMap.put("dataid:=", dataid);
		whereMap.put("matter:=", checkHistory.getMatter());
		List<CheckHistoryEntity> checkHistoryList = checkHistoryService.getEntitys(null, whereMap, null, 1000, 1);
		if (checkHistoryList != null && checkHistoryList.size() > 0) { // 表示当前检查事项名称有记录
			// 获取当前检查状态 0表示未检查、1表示未检查
			String state = checkHistory.getState();
			if ("已检查".equals(state)) {// 只更新当前检查的记录
				// 更新id值
				checkHistory.setId(checkHistoryList.get(0).getId());
				returnCheckHistoryEntity = checkHistoryService.update(checkHistory);
			}else {
				//没有执行检查，就获取数据库中记录。
				returnCheckHistoryEntity = checkHistoryList.get(0);
			}	
		} else {
			returnCheckHistoryEntity = checkHistoryService.add(checkHistory);
		}
		return returnCheckHistoryEntity;
	}
}